layui.use(['layer','laypage','mobile'], function () {
    var mobile = layui.mobile
        , layim = mobile.layim
        , laytpl = layui.laytpl
        , layer = layui.layer
        , laypage = layui.laypage
        ,layrequest = layui.request;
    //这个userCode 是memberUser的account
    //商城那边 传过来的
    var userCode = document.getElementById("account").value;
    var socket = null;  // 判断当前浏览器是否支持WebSocket
    var readOffLineMessage = false;
    if ('WebSocket' in window) {
        var k_host = window.location.host;
        var k_port = window.location.port;
        var wsPath = "ws://" + k_host + k_port + basePath + "/message/" + userCode;
        socket = new WebSocket(wsPath);
    } else {
        alert('该浏览器不支持本系统即时通讯功能，推荐使用谷歌或火狐浏览器！');
    }
    var autoReplay = [
        '您好，我现在有事不在，一会儿再和您联系。'
    ];
    $.post(basePath + '/public/loadMemberChat', {
        account: userCode
    }, function (res) {
        var data = {};
        if (res.code == 0) {
            data = res.data;
        }
        layim.config({
            init: data
            , isNewFriend: false
            , brief: false
            //查看群员接口
            /*,members: {
               url: 'group/getMemberByGroupId'
              ,data: {}
            }*/
            , uploadImage: {
                url: basePath + '/file/uploadFile'
                , type: '' //默认post
            }
            , uploadFile: {
                url: basePath + '/file/uploadFile'
                , type: '' //默认post
            }
        });
    })

    // 连接发生错误的回调方法
    socket.onerror = function () {
        console.log("llws连接失败!");
    };
    // 连接成功建立的回调方法
    socket.onopen = function (event) {
        console.log("llws连接成功!");
    }

    // 接收到消息的回调方法
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        if ((data.messageType) == "chatMessage") {
            layim.getMessage(data);
        } else if (data.messageType == "onlineMessage") {
            layim.setFriendStatus(data.userCode, data.status)
        }
    }

    // 连接关闭的回调方法
    socket.onclose = function () {
        console.log(userCode, "退出连接");
    }
    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        socket.close();
    }

    // 监听发送消息
    layim.on('sendMessage', function (data) {
        $.post(basePath + "/chat/sendMessage", {
            account: userCode,
            toUserCode: data.to.id,
            type: !isNaN(data.to.chatType) ? data.to.chatType : (data.to.userType == 1 ? 2 : 3),
            message: data.mine.content
        }, function (res) {
            if (!res.success) {
                layim.getMessage({
                    system: true,
                    type: data.to.type,
                    content: "消息发送失败,请刷新或稍后再试.",
                    id: data.to.id
                })
            }
        })
    });
    //监听查看更多记录
    layim.on('chatlog', function (data, ul) {
        //弹出一个更多聊天记录面板
        layer.open({
            title:'与 '+ data.name +' 的聊天记录',
            type: 1,
            area:["100%","100%"]
            ,content:'<div class="layim-chat-main" id="message_history" style="bottom: 50px;"><ul id="LAY_view"></ul></div><textarea title="消息模版" id="LAY_tpl" style="display:none;">{{# layui.each(d.data.data, function(index, item){ if(item.id == d.data.id){ }} <li class="layim-chat-mine"><div class="layim-chat-user"><img src="{{ item.avatar }}"><cite><i>{{ layui.data.date(item.timestamp) }}</i>{{ item.username }}</cite></div><div class="layim-chat-text">{{ layui.mobile.layim.content(item.content) }}</div></li> {{# } else { }} <li><div class="layim-chat-user"><img src="{{ item.avatar }}"><cite>{{ item.username }}<i>{{ layui.data.date(item.timestamp) }}</i></cite></div><div class="layim-chat-text">{{ layui.mobile.layim.content(item.content) }}</div></li> {{# } }); }}</textarea><div id="LAY_page" style="margin: 0px 5%; bottom: 0px; position: absolute; width: 90%;  height: 50px;"></div>'
            ,anim: 'up'
            ,style: 'background-color:#dddddd;position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'
        });
        $.post(basePath + "/public/getHistoryCount", {
            userCode: layim.cache().mine.id,
            fromCode: data.id
        }, function (rest) {
            layui.laypage.render({
                elem: 'LAY_page'
                , groups: 2
                , prev: "←"
                , next:"→"
                , limit: 30
                , count: rest.data ? rest.data : 0 //数据总数，从服务端得到
                , jump: function (obj) {
                    $.post(basePath + "/public/getHistory", {
                        "param[userCode]": layim.cache().mine.id,
                        "param[fromCode]": data.id,
                        page: obj.curr,
                        limit: obj.limit
                    }, function (res) {
                        if (res.success) {
                            var html = laytpl(LAY_tpl.value).render({
                                data: {
                                    data:res.data.reverse(),
                                    id: layim.cache().mine.id
                                }
                            });
                            $('#LAY_view').html(html);
                            scrollBottom();
                        }
                    })
                    scrollBottom();
                }
            });
        })
    });

    function scrollBottom() {
        if ($("#message_history").length > 0) {
            var div = $("#message_history")[0];
            div.scrollTop = div.scrollHeight;
        }
    }

    layim.on('ready', function () {
        $.post("/public/getOffLineMessages", {
            account: userCode
        }, function (res) {
            if (res.success) {
                $.each(res.data, function (k, v) {
                    readOffLineMessage = true;
                    layim.getMessage(v);
                });
            }
        });
    });

    layim.on('chatChange', function (event) {
        console.log(event.data)
        if (readOffLineMessage) {
            var data = event.data;
            var url = basePath + "/public/readMessage";
            $.post(url, {
                mineCode: layim.cache().mine.id,
                userCode: data.id
            }, function (res) {
                if (res.success && res.data) {
                    readOffLineMessage = false;
                }
            })
        }
    });

});




